<template>
  <div id="search">
    <div class="data_list">
      <div class="data_inner">
        <van-tabs
          :active="active"
          animated
          color="#226DF0"
          swipeable
          duration="0.6"
          @change="onChange"
        >
          <van-tab
            v-for="(item,index) in titleList"
            :key="index"
            :title="item.tit"
            class="tab_inner"
          >
            <div v-if="myTaskList.records && !myTaskList.records.length" class="nodata">
              <div>
                <img src="../../../static/imgs/tasknull.png" />
                <p>亲空空如也，暂时没有任何任务哦！</p>
              </div>
            </div>
            <div v-else class="tab_data">
              <div style="width:100%;height:52px"></div>
              <div
                v-for="(needItem,needIndex) in myTaskList.records"
                :key="needIndex"
                class="data_inner_item"
              >
                <div class="tab_two">
                  <div class="tab_left1">
                    <img :src="needItem.restaurant_logo" lazy-load mode="widthFix" alt />
                  </div>
                  <div class="tab_right_two">
                    <div @click="goMyTaskDetail(needItem.receive_id,needItem.task_process)">
                      <div class="right_two_title">
                        <span class="blod">
                          {{needItem.task_name}}
                          <span v-if="needItem.task_mold===1">高峰期</span>
                          <span v-if="needItem.task_mold===2">低峰期</span>
                          <span v-if="needItem.task_mold===3">随时</span>
                          <span v-if="needItem.task_mold===4">夜宵</span>
                          <span v-if="needItem.task_mold===5">包夜</span>
                        </span>
                        <span class="sum_btn">
                          <img src="/static/imgs/task/qianIcon.png" mode="widthFix" alt />
                          {{needItem.reward}}
                        </span>
                      </div>
                      <div class="address">
                        <img src="/static/imgs/task/positionicon.png" mode="widthFix" alt />
                        {{needItem.address}}
                      </div>
                      <div class="task_time">
                        任务截止：
                        <span class="blue">{{needItem.task_end_time}}</span>
                        <span class="gray" v-if="needItem.task_process==-5">结束</span>
                      </div>
                    </div>
                    <!-- 任务状态 -->
                    <!-- 0全部任务，1待完成，2审核结果，3已结束 -->
                    <!-- 任务进程 --->
                    <!-- -4管理员中止任务，-3嘉宾取消任务，-1报告拒绝，0待领取，1已领取，2待测试，3.待签到，4已签到，5已签退，6已提交报告待审核，7报告审核通过，8报告驳回，9已发放奖励 -->
                    <!--
                        -6 特邀拒绝 -5测试超时 -4管理员中止任务，-3嘉宾取消任务，-2任务过期未完成，-1报告拒绝，
                        * 1已领取，2待测试，3.待签到，4已签到，5已签退，6已提交报告待审核，
                        * 7报告审核通过，8报告驳回，9已发放奖励
                        待完成：（只会有 0，1，2，3，4，5  状态）  （可点击）
                        0-确认领取  不领取   （只有特邀嘉宾会存在这种状态）
                        1-填写报告，取消
                        2-填写测试 取消
                        3-签到  取消
                        4- 签退 取消
                        5-填写报告 取消
                        审核结果：  6 7 8 9
                        6- 审核中
                        7-通过
                        8-填写报告 （可点击）
                        9-已发放奖励
                        已结束：  9  -5 -4 -3 -2 -1  （不能点击）
                        9- 已发放奖励
                        -5 已结束
                        -6 已拒绝
                        -4 已取消
                        -3 已取消
                        -2 未完成
                    -1 被拒绝-->
                    <!-- <div v-if="taskStatus==='1'"> -->
                    <div>
                      <div
                        class="btn_all"
                        v-if="needItem.task_process==0 || !needItem.receive_time && taskStatus === '1'"
                      >
                        <span class="sign_in" @click="fnTaskBtn(needItem,'qdlq')">确认领取</span>
                        <span class="cabcel_btn" @click="fnTaskBtn(needItem,'blq')">不领取</span>
                      </div>
                      <div v-else>
                        <div
                          class="btn_all"
                          v-if="needItem.task_process==1 || needItem.task_process==5"
                        >
                          <span class="res_time" @click="fnTaskBtn(needItem,'txbg')">
                            <span class="count">
                              <span>&nbsp;&nbsp;剩余时间:</span>
                              <van-count-down
                                format="DD天HH:mm:ss"
                                class="countDown"
                                :time="needItem.report_surplus_date*1000"
                              />
                            </span>
                            <span class="report">填写报告</span>
                          </span>
                          <!-- <span class="write_rep" @click="fnTaskBtn(needItem,'txbg')">填写报告</span> -->
                          <span class="cabcel_btn" @click="fnTaskBtn(needItem,'qt_qx')">取消</span>
                        </div>
                        <div class="btn_all" v-if="needItem.task_process==2">
                          <span class="write_rep" @click="fnTaskBtn(needItem,'txcs')">填写测试</span>
                          <span class="cabcel_btn" @click="fnTaskBtn(needItem,'qt_qx')">取消</span>
                        </div>
                        <div class="btn_all" v-if="needItem.task_process==3">
                          <span class="sign_in" @click="fnTaskBtn(needItem,'qd')">签到</span>
                          <span class="cabcel_btn" @click="fnTaskBtn(needItem,'qt_qx')">取消</span>
                        </div>
                        <div class="btn_all" v-if="needItem.task_process==4">
                          <span class="sign_in" @click="fnTaskBtn(needItem,'qt')">签出</span>
                          <!-- <span class="cabcel_btn" @click="fnTaskBtn(needItem,'qt_qx')">取消</span> -->
                        </div>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==6">
                        <span class="empty_btn"></span>
                        <span class="status_show">审核中</span>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==7">
                        <span class="empty_btn"></span>
                        <span class="status_show">已通过</span>
                      </div>
                      <div
                        class="btn_all"
                        v-if="needItem.task_process==8"
                        @click="fnTaskBtn(needItem,'tjbg')"
                      >
                        <span class="res_time">
                          <span class="count">
                            <span>&nbsp;&nbsp;剩余时间:</span>
                            <van-count-down
                              format="DD天HH:mm:ss"
                              class="countDown"
                              :time="needItem.report_surplus_date*1000"
                            />
                          </span>
                          <span class="report">提交报告</span>
                        </span>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==9">
                        <span class="empty_btn"></span>
                        <span class="payment">已发放奖励</span>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==-5">
                        <span class="empty_btn"></span>
                        <span class="status_show">已结束</span>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==-6">
                        <span class="empty_btn"></span>
                        <span class="status_show">已拒绝</span>
                      </div>
                      <div
                        class="btn_all"
                        v-if="needItem.task_process==-4||needItem.task_process==-3"
                      >
                        <span class="empty_btn"></span>
                        <span class="status_show">已取消</span>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==-2">
                        <span class="empty_btn"></span>
                        <span class="status_show">未完成</span>
                      </div>
                      <div class="btn_all" v-if="needItem.task_process==-1">
                        <span class="empty_btn"></span>
                        <span class="status_show">被拒绝</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="loading">
                <p class="noMoreData">没有更多的数据了</p>
              </div>
            </div>
          </van-tab>
        </van-tabs>
      </div>
    </div>
    <!--弹窗-->
    <van-dialog id="van-dialog" />
  </div>
</template>
<script>
import { get } from "../../utils/request";
import util from "../../utils/tools";
// import NoData from "@/common/components/noData";
import Dialog from "../../../static/vant/dialog/dialog";
import Toast from "../../../static/vant/toast/toast";
export default {
  components: {},
  data() {
    return {
      titleList: [
        {
          status: "1",
          tit: "待完成"
        },
        {
          status: "2",
          tit: "审核结果"
        },
        {
          status: "3",
          tit: "已结束"
        },
        {
          status: "0",
          tit: "全部"
        }
      ],
      myTaskList: {
        records: []
      },
      searchContent: "",
      booksList: [],
      noBooks: false,
      isClean: false,
      loading: false, // 是否有更多数据
      taskStatus: "1", // 任务状态
      active: 0, // 当前选中
      page: {
        current: 1,
        size: 10
      },
      isLogin: false
    };
  },
  onLoad() {
    this.taskStatus = "1";
    this.myTaskList = {
      records: []
    };
    this.searchContent = "";
    this.booksList = [];
    this.noBooks = false;
    this.isClean = false;
    this.loading = false;
    this.active = 0;
    this.page = {
      current: 1,
      size: 10
    };
  },
  onShow() {
    this.isLogin = wx.getStorageSync("userInfo").token && true;
    if (
      typeof this.$root.$mp.page.getTabBar === "function" &&
      this.$root.$mp.page.getTabBar()
    ) {
      this.$root.$mp.page.getTabBar().setData({
        activeIndex: 1 //对应页面的index
      });
    }
    //切换到第一页然后重新请求
    this.page.current = 1;
    this.fnMyTask(this.taskStatus);
  },
  methods: {
    goMyTaskDetail(id, task_process) {
      wx.setStorageSync("taskId", id); // 任务id 跳转详情传id
      wx.navigateTo({
        url: `/pages/myTaskDetail/main?task_process=${task_process}&taskStatus=${
          this.taskStatus
        }`
      });
    },
    goTestWrite() {
      wx.navigateTo({
        url: "/pages/questionAndReport/main"
      });
    },
    async confirm(event) {
      let searchContent = { req: this.searchContent };
      if (searchContent === "") {
        return;
      }
      let result = await get("/searchBooks", searchContent);
      this.booksList = result.data.books;
      if (!this.booksList.length) {
        this.noBooks = true;
      } else {
        this.noBooks = false;
      }
    },
    // 任务切换
    onChange(event) {
      this.page = {
        current: 1,
        size: 10
      };
      let _status = this.titleList[event.mp.detail.index].status;
      this.taskStatus = _status;
      this.fnMyTask(_status);
    },
    // 我的任务列表 /mobile/api/mybankcard
    fnMyTask(status) {
      if (!this.isLogin) return;
      let _obj = {
        customer_id: wx.getStorageSync("userInfo").customer_id,
        current: this.page.current,
        size: this.page.size,
        status: Number(status),
        lnglat: wx.getStorageSync("lnglat")
        // lnglat: '116.29726,39.865862',
      };
      this.$http
        .post({
          url: "/mobile/api/mytasklist",
          data: _obj
        })
        .then(res => {
          let that = this;
          if (res.code == "RX0000" && res.data.records) {
            let _arr = [];
            for (let val of res.data.records) {
              // val.countDow = that.fnCountDown(
              //   val.task_end_time.replace(/-/g, "/")
              // ); //ios 不支持2020-01-02这格式所以这里得转成2020/01/02
              val.task_end_time = val.task_end_time.replace(" 00:00:00", "");
              val.reward = util.formatCurrency(val.reward);
              _arr.push(val);
            }
            if (this.page.current == "1") {
              this.myTaskList = res.data;
              this.myTaskList.records = _arr;
            } else {
              this.myTaskList.current = res.data.current;
              this.myTaskList.pages = res.data.pages;
              this.myTaskList.records = this.myTaskList.records.concat(_arr);
              this.myTaskList.searchCount = res.data.searchCount;
              this.myTaskList.size = res.data.size;
              this.myTaskList.total = res.data.total;
            }
            this.page.current++; // 分页参数
          } else {
            wx.showToast({
              title: res.data
            });
          }
        });
    },
    // 格式化时间戳
    fnCountDown(t) {
      let _sTime = new Date().getTime(); //现在时间（时间戳）
      let _eTime = new Date(t).getTime();
      return _eTime - _sTime > 0 ? _eTime - _sTime : "00:00:00";
    },
    // 任务按钮
    fnTaskBtn(obj, btn) {
      let _level = wx.getStorageSync("userInfo").level;
      let _paramObj = {
        url: "",
        data: { id: "" }
      };
      _paramObj.data.id = obj.id;
      if (btn === "qdlq") {
        // 特邀嘉宾 如果是我的任务列表展示的任务 都掉特邀嘉宾领取任务的接口
        _paramObj.url = "/mobile/api/claimtask";
        _paramObj.data.id = obj.receive_id;
        this.fnReceiverTask(obj, _paramObj, `确定领取${obj.task_name}任务`);
      }
      if (btn === "blq") {
        if (obj.task_process == 0 && _level === 40) {
          _paramObj.url = "/mobile/api/cancelspecify";
          _paramObj.data.id = obj.receive_id;
          this.fnReceiverTask(
            obj,
            _paramObj,
            `确定选择不领取${obj.task_name}任务?`
          );
        } else {
          _paramObj.url = "/mobile/api/canceltask";
          _paramObj.data.id = obj.receive_id;
          (_paramObj.data.customer_id = wx.getStorageSync(
            "userInfo"
          ).customer_id),
            this.fnReceiverTask(
              obj,
              _paramObj,
              `确定选择不领取${obj.task_name}任务?`
            );
        }
      }
      if (btn === "qd") {
        _paramObj.url = "/mobile/api/tasksign";
        (_paramObj.data.customer_id = wx.getStorageSync(
          "userInfo"
        ).customer_id),
          // _paramObj.data.lnglat = wx.getStorageSync('userInfo').lnglat,
          (_paramObj.data.lnglat = wx.getStorageSync("lnglat")),
          (_paramObj.data.id = obj.receive_id),
          (_paramObj.data.type = 0);
        this.fnReceiverTask(obj, _paramObj, "您在签到时必须使用本手机");
      }
      if (btn === "qt") {
        _paramObj.url = "/mobile/api/tasksign";
        (_paramObj.data.customer_id = wx.getStorageSync(
          "userInfo"
        ).customer_id),
          (_paramObj.data.lnglat = wx.getStorageSync("lnglat")),
          (_paramObj.data.id = obj.receive_id),
          (_paramObj.data.type = 1);
        this.fnReceiverTask(obj, _paramObj, "您在签退时必须使用本手机");
      }
      if (btn === "qt_qx") {
        _paramObj.url = "/mobile/api/canceltask";
        _paramObj.data.customer_id = wx.getStorageSync("userInfo").customer_id;
        _paramObj.data.id = obj.receive_id;
        this.canceltaskTask(obj, _paramObj);
      }
      if (btn === "txbg") {
        wx.navigateTo({
          url: `/pages/questionAndReport/main?id=${obj.id}&receive_id=${
            obj.receive_id
          }&type=1&receive_time=${obj.receive_time}`
        });
      }
      if (btn === "tjbg") {
        wx.navigateTo({
          url: `/pages/questionAndReport/main?id=${obj.id}&receive_id=${
            obj.receive_id
          }&type=2&receive_time=${obj.receive_time}`
        });
      }
      if (btn === "txcs") {
        // id	String	是	门店任务ID
        // type	Int	获取类型	1未提交答案查看
        // 2已提交答案查看
        let _obj = {
          id: obj.id,
          rid: obj.receive_id,
          type: 1
        };
        wx.setStorageSync("testObj", _obj); // 获取 小测试需要的参数
        wx.navigateTo({
          url: "/pages/testDetail/main"
        });
      }
    },
    // 领取任务
    fnReceiverTask(obj, paramObj, message, textbtn) {
      let _isAuth = wx.getStorageSync("userInfo").auth_status;
      if (_isAuth) {
        // this.$root.$mp.page.selectComponent('#captcha').reset()
        if (this.taskStatus == 1) {
          Dialog.confirm({
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            message: message
          })
            .then(() => {
              this.$http
                .post({
                  url: paramObj.url,
                  data: paramObj.data
                })
                .then(res => {
                  if (res.code == "RX0000") {
                    //重新获取当前任务列表
                    this.page = {
                      current: 1,
                      size: 10
                    };
                    this.fnMyTask(this.taskStatus);
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: res.data
                    });
                  }
                });
            })
            .catch(() => {});
        } else {
          Dialog.alert({
            message: "该任务已被领完，下次早点来哦！☹"
          }).then(() => {});
        }
      } else {
        Dialog.confirm({
          confirmButtonText: "去实名",
          cancelButtonText: "取消",
          message: "您还未做实名认证，请先完成实名认证"
        })
          .then(res => {
            wx.navigateTo({
              url: "/pages/realName/main"
            });
          })
          .catch(() => {});
      }
    },
    // 取消任务
    canceltaskTask(obj, paramObj) {
      Dialog.confirm({
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        message: "您确定要取消" + obj.task_name + "任务？"
      })
        .then(() => {
          this.$http
            .post({
              url: paramObj.url,
              data: paramObj.data
            })
            .then(res => {
              if (res.code == "RX0000") {
                //重新获取当前任务列表
                this.page = {
                  current: 1,
                  size: 10
                };
                this.fnMyTask(this.taskStatus);
              } else {
                wx.showToast({
                  icon: "none",
                  title: res.data
                });
              }
            });
        })
        .catch(() => {});
    }
  },
  watch: {
    searchContent() {
      this.isClean = this.searchContent.length ? true : false;
    }
  },
  onReachBottom() {
    this.loading = false;
    if (!this.loading && this.page.current <= this.myTaskList.pages) {
      this.fnMyTask(this.taskStatus);
    } else {
      this.loading = true;
    }
  }
};
</script>
<style lang="less">
#search {
  background: #f9f9f9;
  .data_list {
    background: #f9f9f9;
    .data_inner {
      .van-tab--active {
        color: #226df0;
        font-weight: bolder;
        font-size: 16px;
        font-weight: 500;
      }
      .van-tabs__wrap {
        position: fixed !important;
        width: 100%;
        top: 0;
        left: 0;
        z-index: 1;
      }
      .tab_inner {
        padding: 0;
        box-sizing: border-box;
        .tab_data {
          width: 100%;
          box-sizing: border-box;
          overflow: hidden;
          .data_inner_item {
            box-sizing: border-box;
            width: 100%;
            box-sizing: border-box;
            background: #f9f9f9;
            padding: 0 5px;
            box-sizing: border-box;
            margin-bottom: 9px;
            .tab_two {
              width: 100%;
              display: flex;
              justify-content: space-between;
              overflow: hidden;
              background: #fff;
              padding: 27px 10px 12px;
              box-sizing: border-box;
              .tab_left1 {
                width: 68px;
                & > img {
                  width: 100%;
                  vertical-align: middle;
                  border-radius: 10%;
                }
              }
              .tab_right_two {
                flex: 1;
                margin-left: 6px;
                .right_two_title {
                  width: 100%;
                  display: flex;
                  padding: 1px 0 0 0;
                  justify-content: space-between;
                  align-items: center;
                  font-size: 15px;
                  color: #333;
                  .blod {
                    overflow: hidden;
                    display: -webkit-box;
                    text-overflow: ellipsis;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    white-space: normal;
                  }
                  .sum_btn {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    align-self: flex-start;
                    color: #db4a37;
                    font-size: 14px;
                    text-align: center;
                    img {
                      width: 9px;
                      margin: 0 5px 0 0;
                      vertical-align: middle;
                    }
                  }
                }
                .address {
                  color: #999;
                  font-size: 24rpx;
                  display: flex;
                  align-items: center;
                  padding: 9px 0;
                  img {
                    width: 10px;
                    margin: 0 5px 0 0;
                  }
                }
                .task_time {
                  color: #999;
                  font-size: 10px;
                  .blue {
                    color: #999;
                    font-size: 10px;
                  }
                  & > .gray {
                    text-align: center;
                    font-size: 9px;
                    display: inline-block;
                    width: 31px;
                    height: 13px;
                    color: #999999;
                    background: #ececec;
                    margin-left: 3px;
                    border-radius: 1.8px;
                  }
                }
                .btn_all {
                  // height: 40px;
                  // line-height: 40px;
                  display: flex;
                  align-items: center;
                  padding: 10px 0 0 0;
                  justify-content: flex-end;
                  & > span {
                    display: inline-block;
                    height: 20px;
                    font-size: 10px;
                    line-height: 20px;
                    text-align: center;
                  }
                  .empty_btn {
                    width: 65px;
                    margin-left: 120px;
                  }
                  .status_show {
                    width: 65px;
                    font-size: 12px;
                    margin-left: 10px;
                    color: #666;
                    text-align: right;
                  }
                  .payment {
                    width: 75px;
                    font-size: 10px;
                    margin-left: 10px;
                    color: #db4a37;
                    text-align: right;
                  }
                  .sign_out {
                    width: 65px;
                    border-radius: 10px;
                    margin-left: 10px;
                    color: #5696ff;
                    border: 1px solid #5696ff;
                  }
                  .write_rep {
                    width: 65px;
                    border-radius: 10px;
                    margin-left: 120px;
                    color: #5696ff;
                    border: 1px solid #5696ff;
                  }
                  .sign_in {
                    width: 65px;
                    border-radius: 10px;
                    margin-left: 120px;
                    color: #5696ff;
                    border: 1px solid #5696ff;
                  }
                  .cabcel_btn {
                    width: 65px;
                    border-radius: 10px;
                    margin-left: 10px;
                    color: #666;
                    border: 1px solid #ccc;
                  }
                  .res_time {
                    font-size: 10px;
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                  }
                  .res_time > .count {
                    display: inline-flex;
                    color: #5696ff;
                    border-radius: 10px 0 0 10px;
                    padding: 0 9px;
                    background: #cde1ff;
                  }
                  .res_time .report {
                    display: inline-block;
                    background: linear-gradient(
                      90deg,
                      rgba(46, 179, 251, 1) 0%,
                      rgba(25, 91, 252, 1) 100%
                    );
                    border-radius: 0 10px 10px 0;
                    padding: 0 9px;
                    color: #fff;
                  }
                  .sub_rep {
                    width: 60px;
                    background: linear-gradient(to right, #2eb3fb, #195bfc);
                    color: #fff;
                    border-radius: 0px 10px 10px 0px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
.nodata {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  height: calc((100vh - 110px));
  div {
    margin: auto;
    img {
      width: 96px;
      height: 144px;
    }
    p {
      color: #666666;
      font-size: 14px;
      margin-top: 16px;
    }
  }
}
.noMoreData {
  text-align: center;
  font-size: 30rpx;
  color: #999999;
  padding: 20rpx 0;
}
</style>
